<template>
  <div class="login">
    <!-- <stars-bg class="stars-bg"></stars-bg> -->
    <!-- <img class="login-bg" src="../../assets/login-bg.jpg" alt="" /> -->

    <div class="login-form" v-if="formType == 1">
      <h2 class="login-form-title">登录</h2>
      <el-form
        size="large"
        :model="userData"
        :rules="rules"
        label-width="auto"
        label-position="top"
        ref="formRef"
      >
        <el-form-item prop="username" label="账号">
          <el-input size="large" placeholder="请输入名称" v-model="userData.username"> </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input size="large" placeholder="请输入密码" show-password v-model="userData.password">
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha" label="验证码" v-if="isShowCaptcha">
          <el-input size="large" placeholder="请输入验证码" v-model="userData.captcha">
            <template #append>
              <div class="captcha" v-loading="captchaLoginLoading" @click="getCreateLoginCaptcha">
                <img class="captcha-img" :src="captchaLoginBase64" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>
        <div class="login-form-handle">
          <el-checkbox
            v-model="rememberPassword"
            label="记住密码"
            true-label="1"
            false-label="0"
            @change="onRememberPasswordChange"
          />
          <span class="forgot-password">忘记密码</span>
        </div>
        <el-button
          class="button"
          type="primary"
          size="large"
          @click="handleEnd"
          :loading="submitLoading"
        >
          {{ submitLoading ? '登录中...' : '登 录' }}
        </el-button>
        <el-button class="button" size="large" @click="toFormRegister"> 注 册 </el-button>
      </el-form>
    </div>

    <div class="login-form" v-if="formType == 2">
      <h2 class="login-form-title">注册</h2>
      <el-form
        size="large"
        :model="registerData"
        :rules="registerRules"
        label-width="auto"
        label-position="top"
        ref="registerFormRef"
      >
        <el-form-item prop="username" label="账号">
          <template #label>
            <span>
              账号 (
              <span class="form-item-desc">
                注意：建议使用名字的拼音，或者字母加手机号，如a188888
              </span>
              )
            </span>
          </template>

          <el-input size="large" placeholder="请输入账号" v-model="registerData.username">
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            size="large"
            placeholder="请输入密码"
            show-password
            v-model="registerData.password"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="小程序用户ID">
          <template #label>
            <span @click="getMiniID" style="display: flex; align-items: center">
              小程序用户ID
              <span
                style="display: flex; align-items: center; margin-left: 10px"
                class="is-primary-text is-cursor-pointer"
              >
                如何获取
                <el-icon><QuestionFilled /></el-icon>
              </span>
            </span>
          </template>
          <el-input size="large" placeholder="请输入小程序用户ID" v-model="registerData.nickname">
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha" label="验证码">
          <el-input size="large" placeholder="请输入验证码" v-model="registerData.captcha">
            <template #append>
              <div class="captcha" v-loading="captchaLoading" @click="getCreateCaptcha">
                <img class="captcha-img" :src="captchaBase64" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-button
          class="button"
          type="primary"
          size="large"
          @click="handleRegisterEnd"
          :loading="registerLoading"
        >
          {{ submitLoading ? '注册中...' : '注 册' }}
        </el-button>
        <el-button class="button" size="large" @click="toFormLogin"> 登 录 </el-button>
      </el-form>
    </div>

    <c-dialog title="获取小程序ID指引" :width="600" name="guide-popup">
      <guide-popup :type="1"></guide-popup>
    </c-dialog>
  </div>
</template>

<script setup name="login">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import starsBg from '@/components/canvas-demo/stars-bg.vue';
import GuidePopup from '@/components/guide-popup/index.vue';
import { QuestionFilled } from '@element-plus/icons-vue';

// variable
import { REMEMBER_PASSWORD } from '@/config/storage-variable.js';
import { LoginErrCode } from '@/config/global-variable.js';

// global
import { useGlobalStore } from '@/pinia/modules/global.js';
const globalStore = useGlobalStore();

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// api
import { login, registerUser, createCaptcha } from '@/apis/user.js';

// 账号&密码
const userData = reactive({
  username: '',
  password: '',
  captcha: '',
});

const registerData = reactive({
  username: '',
  password: '',
  captcha: '',
  nickname: '',
});

const rememberPassword = ref('1');

const formType = ref(1);

// 跳转
const toSkip = () => {
  // let path = globalStore.lastPagePath;
  router.push('/materal-center');
  ElMessage.success('登录成功');
};

const rules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'change' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'change' }],
});

const registerRules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'change' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'change' }],
  nickname: [{ required: true, message: '请输入小程序用户ID', trigger: 'change' }],
});

const onRememberPasswordChange = () => {
  localStorage.setItem(REMEMBER_PASSWORD, rememberPassword.value);
};

const formRef = ref();
const submitLoading = ref(false);
const isShowCaptcha = ref(false);
const handleEnd = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitLoading.value = true;
    const res = await login(userData);
    submitLoading.value = false;

    if (res.errCode == 0) {
      localStorage.setItem('uni_id_token', res.newToken.token);
      const expired = JSON.stringify({
        type: typeof res.newToken.tokenExpired,
        data: res.newToken.tokenExpired,
      });
      localStorage.setItem('uni_id_token_expired', expired);

      if (rememberPassword.value == '1') {
        const loginUserInfo = JSON.stringify(userData);
        localStorage.setItem('login_user_info', loginUserInfo);
      }

      toSkip();
    } else {
      ElMessage.error(LoginErrCode[res.errCode]);
      if (res.errCode == 'uni-id-captcha-required') {
        isShowCaptcha.value = true;
        getCreateLoginCaptcha();
      }
    }
  });
};

const registerFormRef = ref();
const registerLoading = ref(false);
const handleRegisterEnd = () => {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return;
    registerLoading.value = true;
    const res = await registerUser(registerData);
    registerLoading.value = false;

    if (res.errCode == 0) {
      localStorage.setItem('uni_id_token', res.newToken.token);
      const expired = JSON.stringify({
        type: typeof res.newToken.tokenExpired,
        data: res.newToken.tokenExpired,
      });
      localStorage.setItem('uni_id_token_expired', expired);

      if (rememberPassword.value == '1') {
        const loginUserInfo = JSON.stringify(registerData);
        localStorage.setItem('login_user_info', loginUserInfo);
      }

      toSkip();
    } else {
      ElMessage.error(LoginErrCode[res.errCode]);
    }
  });
};

const captchaLoading = ref(false);
const captchaBase64 = ref('');
const getCreateCaptcha = async () => {
  captchaLoading.value = true;
  const res = await createCaptcha({
    scene: 'register',
  });
  captchaLoading.value = false;
  if (res.code == 0) {
    captchaBase64.value = res.captchaBase64;
  }
};

const captchaLoginLoading = ref(false);
const captchaLoginBase64 = ref('');
const getCreateLoginCaptcha = async () => {
  captchaLoginLoading.value = true;
  const res = await createCaptcha({
    scene: 'login-by-pwd',
  });
  captchaLoginLoading.value = false;
  if (res.code == 0) {
    captchaLoginBase64.value = res.captchaBase64;
  }
};

const toFormLogin = () => {
  formType.value = 1;
};

const toFormRegister = () => {
  formType.value = 2;
  getCreateCaptcha();
};

const getMiniID = () => {
  modalStore.openModal('guide-popup');
};

const init = () => {
  // 检查是否存在账号&密码
  const loginUserInfo = localStorage.getItem('login_user_info');
  // 检查是否记住密码
  const _rememberPassword = localStorage.getItem(REMEMBER_PASSWORD);
  console.log(_rememberPassword, '_rememberPassword');
  if (loginUserInfo) {
    const { username, password } = JSON.parse(loginUserInfo);
    userData.username = username;
    userData.password = password;
  }
  rememberPassword.value = _rememberPassword || '0';
};

init();
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background-color: #f0f3fc;

  .stars-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .login-bg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    object-fit: cover;
  }

  .login-form {
    width: 90%;
    max-width: 460px;
    z-index: 1;
    padding: 40px 20px;
    box-sizing: border-box;
    background-color: rgb(255, 255, 255);
    // opacity: 0.9;
    // background-color: rgb(255, 255, 255, 0.15);
    border-radius: 12px;
    box-shadow: var(--el-box-shadow-lighter);
    transition: var(--el-transition-duration);
    // z-index: 9999;
    // position: absolute;
    // right: 10%;
    // top: 50%;
    // transform: translateY(-50%);

    :deep(.el-form) {
      width: 100%;
    }

    :deep(.el-form-item) {
      margin-bottom: 20px;
      // &:nth-of-type(2) {
      //   margin-bottom: 0px;
      // }
    }

    :deep(.el-input-group__append) {
      padding: 0;
    }

    // :deep(.el-button),
    // :deep(.el-checkbox__inner),
    // :deep(.el-input-group__prepend),
    // :deep(.el-input__wrapper) {
    //   background-color: rgba(255, 255, 255, 0.15);
    //   box-shadow: none !important;
    // }

    // :deep(.el-checkbox__input .el-checkbox__inner),
    // :deep(.el-button) {
    //   border: 1px solid rgba(255, 255, 255, 0.15);
    // }

    // :deep(.el-button) {
    //   color: #fff;
    // }

    // :deep(.el-button--primary) {
    //   background-color: rgb(64, 158, 255, 0.6);
    // }

    // :deep(.el-input__inner) {
    //   color: #fff;
    // }
  }

  .login-form-title {
    font-size: 18px;
    color: var(--color-primary);
    margin-bottom: 26px;
    margin-top: 0;
    font-weight: 400;
  }

  .login-form-handle {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
  }

  .forgot-password {
    cursor: pointer;
    color: var(--color-primary);
    font-size: 14px;
    user-select: none;
  }

  .button {
    text-align: center;
    width: 100%;
    margin: 16px 0 0 0;
    font-weight: 800;
  }

  .captcha {
    width: 100px;
    height: 100%;
  }

  .captcha-img {
    width: 100%;
    height: 100%;
  }

  .form-item-desc {
    color: #999;
    font-size: 12px;
  }
}
</style>
